import { _decorator, Component, Node,  geometry, input, Input, EventTouch, PhysicsSystem, EventMouse, find, Layers, MeshRenderer, Color } from 'cc';
import WorldManager from './WorldManager';
import { Plane } from './Plane';
import { CameraManager } from './CameraManager';

const { ccclass, property } = _decorator;

@ccclass('TouchPicker')
export class TouchPicker extends Component {
   
    private _ray: geometry.Ray = new geometry.Ray();

    private pickerNode: Node;
    private lastColor: Color;

    private isPick: boolean = false;

    private startTime: number = 0;
    start() {
      
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.on(Input.EventType.TOUCH_CANCEL, this.onTouchCancel, this)
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);

    }

    onTouchStart() {
        this.startTime = new Date().getTime()
    }
    onTouchMove() {

    }

    onTouchCancel() {

    }

    onTouchEnd(event: EventTouch) {
        let now = new Date().getTime()
        if (now - this.startTime > 300) {
            return
        }

        const touch = event.touch!;
        this.handleRay(touch.getLocationX(), touch.getLocationY())
    }

    handleRay(x: number, y: number) {
        CameraManager.instance.camera.screenPointToRay(x, y, this._ray);
        if (PhysicsSystem.instance.raycastClosest(this._ray)) {
            const result = PhysicsSystem.instance.raycastClosestResult;
            let node = result.collider.node

            if (node.layer == Layers.Enum.Plane) {
                this.hitPlane(node)
            }



        } else {
            console.log('raycast does not hit  node !');
        }
    }

    hitPlane(node: Node) {
        let plane = node.getComponent(Plane)
        if (node.name == WorldManager.instance.pickerNode?.name) {

            plane.revertColor()
            WorldManager.instance.pickerNode = null
            find('Canvas/addPanel').active = false
            return

        }

        if (WorldManager.instance.pickerNode) {
            WorldManager.instance.pickerNode.getComponent(Plane).revertColor()
        }




        plane.changeColor()

        WorldManager.instance.pickerNode = node
        find('Canvas/addPanel').active = true
    }
}

